// pages/index/zoon/zoon.js
import { axios } from '../../../utils/ajax.js'
import { gettime } from '../../../utils/djs.js'
import { checklogin } from '../../../utils/login.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        specialId: '',   //测试5696
        title: '',
        data: {},
        goodslist: [],
        coupons: [],    //优惠券
        brands: [],  //品牌墙
        brandlist: '',
        sortType: 0, // 排序
        showStock: true, // 显示有货
        attrType: "", // 筛选类型
        attrTypeId: "", // 筛选项id,
        hascollected: '',   //品牌收藏
        remind: '',       //开售提醒,
        filterData: '', //筛选目录，带到下个页面
        totopshow: '',
        page: 1,
        totalPages: '',
        canload: true,
        //倒计时
        djstitle: '距离本场立减开始',
        djscontent: '',
        isend: false,
        hotGoods: [],
        //是否显示开售提醒按钮
        showremind:false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options)
        let { linkId, title = '' } = options
        this.setData({
            specialId: linkId,
            title: title
        })
        let { userid = '', token = '' } = wx.getStorageSync('userinfo') 
        axios({
            //请求专区商品列表信息
            url: '/goods/special',
            data: {
                specialId: this.data.specialId,
                page: 1,
                sortType: this.data.sortType,
                showStock: this.data.showStock,
                attrType: this.data.attrType,
                attrTypeId: this.data.attrTypeId,
                userid: userid,
                token: token
            }
        }).then((res) => {
            console.log(res)
            this.setData({
              data: res.data,
              coupons: res.data.coupons,
              goodslist: res.data.data,
              totalPages: res.data.totalPages,
              title: res.data.title,
              hascollected: res.data.isLike,
              remind: res.data.isRemind,
              hotGoods: res.data.hotSellingGoods
            })
            wx.setNavigationBarTitle({
              title: this.data.title
            })
            
            let openTime = res.data.openTime
            let closeTime = res.data.closeTime
            let targettime = openTime > parseInt(new Date().getTime() / 1000) ? openTime : closeTime
            this.setData({
              djstitle: openTime > parseInt(new Date().getTime() / 1000) ? '距离本场立减开始' : closeTime > parseInt(new Date().getTime() / 1000) ? '距离本场立减结束' : '本场已结束',
              showremind: openTime > parseInt(new Date().getTime() / 1000) ? true:false
            })
            if (gettime(targettime)) {
              this.setData({
                djscontent: gettime(targettime)
              })
            }
            //倒计时
            let goodstimer = setInterval(() => {
                let targettime = openTime > parseInt(new Date().getTime() / 1000) ? openTime : closeTime
                this.setData({
                    djstitle: openTime > parseInt(new Date().getTime() / 1000) ? '距离本场立减开始' : closeTime > parseInt(new Date().getTime() / 1000) ? '距离本场立减结束' : '本场已结束',
                    showremind: openTime > parseInt(new Date().getTime() / 1000) ? true : false
                })
                if (gettime(targettime)) {
                    this.setData({
                        djscontent: gettime(targettime)
                    })
                } else {
                    clearInterval(goodstimer)
                    //已经结束
                    this.setData({
                        isend: true
                    })
                }
            }, 1000)

            //品牌墙变化二维数组
            let brands = res.data.brands
            let group = Math.ceil(brands.length / 4)
            let newbrands = new Array(group);
            for (var i = 0; i < group; i++) {
                newbrands[i] = []
            }
            brands.forEach((val, index) => {
                let num = Math.floor(index / 4)
                newbrands[num].push(val)
            })
            this.setData({
                brands: newbrands,
                brandlist: res.data.brands
            })
            if (this.data.page == this.data.totalPages) {
                this.setData({
                    canload: false
                })
            }
        })

        //请求筛选信息
        axios({
            url: '/goods/filterGoods',
            data: {
                specialId: this.data.specialId
            }
        }).then((res) => {
            let filterData = res.data.data
            // 初始化筛选数据
            filterData.forEach(item => {
                item.attr.forEach(it => {
                    it.selected = it.id == '' ? true : false
                })
            })
            this.setData({
                filterData: filterData
            }, () => {
                filterSetData(this, 0)
            })
        })
    },

    // 用户点击右上角分享
    onShareAppMessage: function (res) {
        let { specialId, title } = this.data;
        console.log(title)
        return  {
          title: title,
          path: `/pages/home/zone/zone?linkId=${specialId}&title=${title}`
        }
    },
    //领取优惠券
    getcoupon(e) {
        checklogin().then((res) => {
            let { couponId, receive } = e.currentTarget.dataset;
            console.log(couponId, receive)
            //没领过
            if (!receive) {
                axios({
                    url: '/coupon/getInSpecial',
                    data: {
                        couponId: couponId,
                        userid: res.userid,
                        token: res.token,
                    }
                }).then((res) => {
                    console.log(res)
                    let coupons = this.data.coupons
                    coupons.find(x => x.couponId == couponId).receive = 1
                    this.setData({
                      coupons: coupons
                    })
                    wx.showToast({
                        title: res.data.message,
                        icon: 'none'
                    })
                })
            }else{
              wx.showToast({
                title: '已经领过优惠券',
                icon:"none"
              })
            }
        })
    },
    //开售提醒
    remind() {
        checklogin().then((res) => {
            console.log(res)
            let remind = this.data.remind
            console.log(remind)
            axios({
                url: '/goods/salesRemind',
                data: {
                    userId: res.userid,
                    token: res.token,
                    specialId: this.data.specialId,
                    enable: remind ? 0 : 1
                }
            }).then((res) => {
                // console.log(res)
                wx.showToast({
                    title: res.data.messgae,
                    icon: "none"
                })
            })
        })
    },
    //收藏
    collect() {
        checklogin().then((res) => {
            //   console.log(res)
            let hascollected = this.data.hascollected
            console.log(hascollected)
            axios({
                url: '/brand/collect',
                data: {
                    userid: res.userid,
                    token: res.token,
                    brandId: this.data.data.brandId,
                    type: hascollected ? 0 : 1
                }
            }).then((res) => {
                console.log(res)
                this.setData({
                  hascollected: !this.data.hascollected
                })
                wx.showToast({
                    title: res.data.message,
                    icon: "none"
                })
            })
        })
    },
    onPageScroll(e) {
        this.setData({
            totopshow: e.scrollTop > 800 ? true : false
        })
    },
    onReachBottom: function () {
        console.log(this.data.totalPages)
        let page = this.data.page
        let totalPages = this.data.totalPages
        if (page < totalPages) {
            page++
            this.setData({
                page: page
            })
            axios({
                url: '/goods/special',
                data: {
                    specialId: this.data.specialId,
                    page: page,
                    sortType: this.data.sortType,
                    showStock: this.data.showStock,
                    attrType: this.data.attrType,
                    attrTypeId: this.data.attrTypeId
                }
            }).then((res) => {
                let goodslist = this.data.goodslist.concat(res.data.data)
                this.setData({
                    goodslist: goodslist
                })
            })
        } else {
            this.setData({
                canload: false
            })
        }
    },

    filterComponentChange: function (e) {
        // console.log('筛选组件改变：', e.detail)
        this.setData({
            sortType: e.detail.sorttype,
            showStock: e.detail.showstock
        }, () => {
            filterGoodsList(this)
        })
    },
    // 筛选更新数据
    changeFilterData: function (data) {
        this.setData({
            filterData: data
        }, () => {
            filterSetData(this, 1)
        })
    },
    // 清空筛选
    clearchoose() {
        let filterData = this.data.filterData;
        filterData.forEach(item => {
            item.attr.forEach(it => {
                it.selected = it.id == '' ? true : false
            })
        })
        this.setData({
            attrType: '',
            attrTypeId: '',
            filterData: filterData
        }, () => {
            filterSetData(this, 1)
        })
    },
    //爆款商品进详情
    jumpgood (e){
      let goodid = e.currentTarget.dataset.goodid
      console.log(goodid)
      wx.navigateTo({
        url: `../goodsDetail/goodsDetail?linkId=${goodid}`,
      })
    }
})

function filterSetData(that, update) {
    let filterData = that.data.filterData;

    // 展示经过筛选的数据
    let selectedData = [];
    for (var i = 0; i < filterData.length; i++) {
        selectedData[i] = {};
        selectedData[i].name = filterData[i].name;
        let attr = [];
        for (var j = 0; j < filterData[i].attr.length; j++) {
            if (filterData[i].attr[j].selected == true && filterData[i].attr[j].id != '') {
                attr.push(filterData[i].attr[j])
            }
        }
        selectedData[i].attr = attr;
    }

    // 重置attrType和attrTypeId
    let attrType = filterData.map(item => item.type).join('|');
    let attrTypeId = selectedData.map(item => item.attr);
    attrTypeId.forEach((item, index) => {
        attrTypeId[index] = item.map(it => it.id).join(',');
    })
    attrTypeId = attrTypeId.join('|');

    that.setData({
        filterData: filterData,
        selectedData: selectedData,
        attrType: attrType,
        attrTypeId: attrTypeId
    }, () => {
        if (update) {
            filterGoodsList(that)
        }
    })
}

function filterGoodsList(that) {
  console.log("sortType:" + that.data.sortType)
  console.log("attrType:" + that.data.attrType)
  console.log("attrTypeId:" + that.data.attrTypeId)
    axios({
        url: '/goods/special',
        data: {
            specialId: that.data.specialId,
            page: 1,
            sortType: that.data.sortType,
            showStock: that.data.showStock,
            attrType: that.data.attrType,
            attrTypeId: that.data.attrTypeId
        }
    }).then((res) => {
        that.setData({
            data: res.data,
            goodslist: res.data.data,
            totalPages: res.data.totalPages,
            canload: res.data.page == res.data.totalPages ? false : true
        })
        wx.pageScrollTo({
            scrollTop: 0,
            duration: 0
        })
    })
}